//
//  RealmDataViewController.swift
//  RealmDemo
//
//  Created by lete on 2020/12/18.
//

import Foundation
import UIKit

import RealmSwift

class RealmDataViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        // Realm 数据库的配置
        //        // 主相册
        //        let mainPhotos = SBSingleID.singleID() + "-main**" + userID
        //        RealmTools.configRealm(userID: mainPhotos, schemaVersion: 0) { (migration, oldSchemaVersion) in
        //        }
        //
        // 一开始生成
        
        
        
        let subPhotos = SBSingleID.singleID() + "-sub**"  + userID
        
        let urlForDocument = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).first! as URL
        let dUrl = urlForDocument.appendingPathComponent(subPhotos + ".realm")
        /// 不存在伪相册
        if FileManager.default.fileExists(atPath: dUrl.path) == false{
            // 伪相册
            RealmTools.configRealm(userID: SBSingleID.singleID() + "-sub**", schemaVersion: 0) { (migration, oldSchemaVersion) in
            }
            print("存储路径：\(RealmTools.fileURL?.path ?? "没有路径")")
            
            // 登录后切换
            // 伪相册
            do {
                let newUrl = RealmTools.fileURL!.deletingLastPathComponent().appendingPathComponent(subPhotos + ".realm")
                try FileManager.default.moveItem(at: RealmTools.fileURL!, to:newUrl )
            } catch  {
                debugPrint("没有这个路径--->>>>> \(error)")
            }
            RealmTools.configRealm(userID: subPhotos)
            //            RealmTools.configRealm(userID: subPhotos, schemaVersion: 0) { (migration, oldSchemaVersion) in
            //            }
            print("存储路径：\(RealmTools.fileURL?.path ?? "没有路径")")
            
        }
        else{
            
            RealmTools.configRealm(userID: subPhotos, schemaVersion: 0) { (migration, oldSchemaVersion) in
            }
            print("已存在伪相册存储路径：\(RealmTools.fileURL?.path ?? "没有路径")")
        }
        
    }
    
    /// 查询所有
    @IBAction func selectedBtn(_ sender: UIButton) {
        
        /// 查询某个对象
        let arr = RealmTools.objects(RouteVO.self)
        print("select-----🚀-----------")
        print(arr)
        print("select-----🚀-----------")
    }
    @IBAction func selected(_ sender: UIButton) {
        
        selectWithCondition()
    }
    
    /// 查询某个对象数据(根据条件)
    func selectWithCondition() {
        let predicate = NSPredicate(format: "appType = 0", argumentArray: nil)
        guard let items = RealmTools.objectsWithPredicate(object: PhotosVO.self, predicate: predicate) else {
            return
        }
        print(items)
    }
    
    /// 带排序条件查询
    func test53() {
        let predicate = NSPredicate(format: "appType = 1", argumentArray: nil)
        guard let items = RealmTools.objectsWithPredicateAndSorted(object: PhotosVO.self, predicate: predicate, sortedKey: "appType", isAssending: false) else {
            return
        }
        print(items)
    }
    
    /// 带分页的查询
    func test54() {
        let predicate = NSPredicate(format: "type = 0", argumentArray: nil)
        guard let items = RealmTools.objectsWithPredicateAndSortedForPages(object: PhotosVO.self, predicate: predicate, sortedKey: "type", isAssending: true, fromIndex: 1, pageSize: 2) else {
            return
        }
        print(items)
    }
    
    @IBAction func addBtn(_ sender: UIButton) {
        
        for i in 0..<6 {
            let route = RouteVO()
            route.route = "喜欢" + String.init(i)
            route.userID = userID
            route.albumName = "喜欢"
            for i in 0..<2 {
                let photos = PhotosVO()
                photos.id = "2309843978981248923uduuds" + String.init(i)
                photos.name = "12345.png"
                photos.format = ".png"
                photos.localPath = "/var/mobile/Containers/Data/Application/F0FE4F6E-6031-426B-ADE7-26AB06CD3424/Documents/喜欢/12345.png"
                route.photosList.append(photos)
            }
            RealmTools.add(route) {
                print("task-----🚀-----------")
                
            }
        }
        
    }
    
    /// 增加更新 Model 内部 List 元素
    @IBAction func albumIntoAdd(_ sender: UIButton) {
        
        guard let items = RealmTools.objects(RouteVO.self) as? Array<RouteVO>, items.count > 0 else {
            return
        }
        items.forEach { (item) in
            if item.route == "喜欢2"{
                
                let photos = PhotosVO()
                photos.id = "2453437837493jjcl"
                photos.name = "4982937.png"
                photos.format = ".png"
                photos.localPath = "/var/mobile/Containers/Data/Application/F0FE4F6E-6031-426B-ADE7-26AB06CD3424/Documents/喜欢2/4982937.png"
                
                RealmTools.updateWithTranstion { (result) in
                    item.photosList.append(photos)
                    print("updata-----🚀-----------")
                }
            }
            
        }
        
    }
    
    
    /// 更新 数据
    @IBAction func updata(_ sender: UIButton) {
        guard let items = RealmTools.objects(RouteVO.self) as? Array<RouteVO>, items.count > 0 else {
            return
        }
        items.forEach { (item) in
            if item.route == "喜欢2"{
                
                let photos = PhotosVO()
                photos.id = "2453437837493jjcl"
                photos.name = "4982937.png"
                photos.format = ".png"
                photos.localPath = "/var/mobile/Containers/Data/Application/F0FE4F6E-6031-426B-ADE7-26AB06CD3424/Documents/喜欢2/4982937.png"
                
                RealmTools.updateWithTranstion { (result) in
                    item.photosList.append(photos)
                    item.uuid = "000000000000000000"
                    print("updata-----🚀-----------")
                }
            }
            
        }
    }
    
    /// 删除 外层 Model 及其关联数据
    @IBAction func del(_ sender: Any) {
        guard let items = RealmTools.objects(RouteVO.self), items.count > 0 else {
            return
        }
        items.forEach { (item) in
            if item["route"] as! String == "喜欢2"{
                let phoList = item["photosList"] as? List<PhotosVO>
                
                /// List 数组转 Array 数组
                var delListArr = Array<PhotosVO>()
                phoList?.forEach({ (p) in
                    let pp = p
                    delListArr.append(pp)
                })
                
                /// 删除里面图片数组
                RealmTools.deleteList(delListArr) {
                    print("delete-----🚀-----------")
                }
                /// 删除外层 Model
                RealmTools.delete(item) {
                    print("delete 大的-----🚀-----------")
                }
            }
        }
    }
    /// 删除 model 内部的 list 元素及关联表
    @IBAction func deleteModelListSomeData(_ sender: UIButton) {
        
        guard let items = RealmTools.objects(RouteVO.self) as? Array<RouteVO>, items.count > 0 else {
            return
        }
        items.forEach { (item) in
            if item.route == "喜欢2"{
                
                var delListArr = Array<PhotosVO>()
                
                RealmTools.updateWithTranstion { (result) in
                    for (index, pModle) in item.photosList.enumerated(){
                        //遍历数组索引和元素
                        if pModle.id == "2453437837493jjcl"{
                            item.photosList.remove(at: index)
                            print("updata-----🚀-----------")
                            delListArr.append(pModle)
                        }
                    }
                    
                    
                }
                RealmTools.deleteList(delListArr, task: {
                    print("delete 内部某个元素-----🚀-----------")
                })
            }
            
        }
    }
    @IBAction func deleteMethod(_ sender: UIButton) {
        deleteWithConditions()
        
    }
    
    /// 根据条件删除对象
    func deleteWithConditions() {
        
       let predicate = NSPredicate(format: "route == '喜欢4'", argumentArray: nil)
       RealmTools.deleteByPredicate(object:  RouteVO.self, predicate: predicate)
   }
    
}


/**
 谓词使用:
 字符串     ====>>>>>>               "route == '喜欢3'"
 
 
 */
